package com.caohx.bms.service;


import com.caohx.bms.pojo.BookCategory;
import com.caohx.bms.repository.BookCategoryRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class BookCategoryService extends IBookCategoryService {

    @Autowired
    private BookCategoryRepository bookCategoryRepository;

    @PostConstruct
    public void logServiceStatus() {
        System.out.println("BookCategoryService is loaded by Spring.");
        if (bookCategoryRepository == null) {
            System.out.println("bookCategoryRepository is null.");
        } else {
            System.out.println("bookCategoryRepository is successfully injected.");
        }
    }

      @Override
    public Page<BookCategory> findCategories(Pageable pageable) {
        // 假设有一个方法将 BookCategory 转换为 BookCategoryDto
        return bookCategoryRepository.findAll(pageable);
    }



    @Override
    public void delete(Long categoryId) {
        if (!bookCategoryRepository.existsById(categoryId)) {
            throw new IllegalArgumentException("图书分类ID不存在: " + categoryId);
        }
        bookCategoryRepository.deleteById(categoryId);
    }

    @Override
    public BookCategory add(BookCategory bookCategory) {
        if (bookCategory == null) {
            throw new IllegalArgumentException("图书分类不能为空");
        }
        return bookCategoryRepository.save(bookCategory);
    }
    @Override
    public BookCategory edit(BookCategory bookCategory) {
        if (bookCategory == null || bookCategory.getId() == null) {
            throw new IllegalArgumentException("图书分类或ID不能为空");
        }
        // 查找现有记录
        BookCategory existingCategory = bookCategoryRepository.findById(bookCategory.getId())
                .orElseThrow(() -> new IllegalArgumentException("图书分类ID不存在: " + bookCategory.getId()));
        // 更新字段
        existingCategory.setName(bookCategory.getName()); // 假设只有 name 字段需要更新
        // 保存并返回更新后的对象
        return bookCategoryRepository.save(existingCategory);
    }
    @Override
    public BookCategory get(Long categoryId) {
        // 根据 categoryId 查询图书分类
        return bookCategoryRepository.findById(categoryId)
                .orElseThrow(() -> new IllegalArgumentException("图书分类ID不存在: " + categoryId));
    }
}
